
module key_debounce (
    input sys_clk,                      //系统时钟
    input sys_rst,                      //系统复位脚
    
    input key,                          //按键输入
    output reg key_pressed_flag,        //按键按下标记
    output reg key_value                //按键值
);

reg [31:0] debounce_delay_count;
reg key_value_reg;

always @ (posedge sys_clk or negedge sys_rst) begin
    if (!sys_rst) begin
        key_value_reg <= 1'b1;
        debounce_delay_count <=  32'd0;
    end
    else begin
        key_value_reg <= key;
        if (key_value_reg != key)               //按键值变化，检测到按键动作（按下或松开),抖动计数值重新加载，计时0.2s
            debounce_delay_count <= 32'd10000000;
        else begin 
            if (debounce_delay_count > 32'b1)
                debounce_delay_count <= debounce_delay_count - 1'b1;
            else
                debounce_delay_count <= debounce_delay_count;
        end
            
    end
end

always @ (posedge sys_clk or negedge sys_rst ) begin
    if (!sys_rst) begin
        key_pressed_flag <= 1'b0;
        key_value <= 1'b1;
    end
    else begin 
        if (debounce_delay_count == 32'b1)   begin   //计数值减为1，抖动计时到
            key_pressed_flag <= 1'b1;
            key_value <= key;
        end
        else begin
            key_pressed_flag <= 1'b0;
            key_value <= key_value;
        end
            
    end
end

endmodule